
import com.jason.entity.Category;
import java.util.List;
import javax.persistence.EntityManager;

/**
 *
 * @author Jason
 *
 */
public class TomcatBean {

    private EntityManager app;

    public TomcatBean(EntityManager app) {
        this.app = app;
    }

    public void create(Category category) {
        app.getTransaction().begin();
        app.persist(category);
        app.getTransaction().commit();
    }

    public List<Category> getAll() {
        app.getEntityManagerFactory().getCache().evictAll();
        return app.createNamedQuery("Category.findAll", Category.class).getResultList();
    }

    public List<Category> getRootNode() {
        app.getEntityManagerFactory().getCache().evictAll();
        return app.createQuery("SELECT o FROM Category o WHERE o.parentCategory is null").getResultList();
    }

    public Category findById(int id) {
        return app.createNamedQuery("Category.findById", Category.class).setParameter("id", id).getSingleResult();

    }

    public void update(Category c) {
        app.getTransaction().begin();
        app.merge(c);
        app.getTransaction().commit();
    }
    public void remove(Category c) {
        app.getTransaction().begin();
        app.remove(app.merge(c));
        app.getTransaction().commit();
    }
}
